/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.yczbj.ycvideoplayer.ability;

import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.ListContainer;
import ohos.bundle.AbilityInfo;

import com.yc.video.bridge.ControlWrapper;
import com.yc.video.config.ConstantKeys;
import com.yc.video.config.VideoInfoBean;
import com.yc.video.player.VideoPlayer;
import com.yc.video.player.VideoViewManager;
import com.yc.video.tool.PlayerUtils;
import com.yc.video.ui.pip.FloatVideoManager;
import com.yc.video.ui.view.BasisVideoController;

import org.yczbj.ycvideoplayer.ConstantVideo;
import org.yczbj.ycvideoplayer.ResourceTable;
import org.yczbj.ycvideoplayer.adapter.VideoRecyclerViewAdapter;
import org.yczbj.ycvideoplayer.fraction.OnItemChildClickListener;

import java.util.List;

/**
 * 4.2 视频列表中自动悬浮播放视频
 *
 * @since 2021-05-10
 */
public class PipListAbility extends BaseAbility implements OnItemChildClickListener {
    private static final int COUNT_NUM = -1;
    private FloatVideoManager mPipManager;
    private VideoPlayer mVideoView;
    private List<VideoInfoBean> mVideos;
    private ListContainer listContainer;
    private int mLastPos = COUNT_NUM;

    @Override
    protected int getLayoutResId() {
        return ResourceTable.Layout_base_recycler_view;
    }

    @Override
    protected void initComponent(Intent intent) {
        super.initComponent(intent);
        mPipManager = FloatVideoManager.getInstance(this);
        mVideoView = VideoViewManager.instance().get(FloatVideoManager.PIP);
        ComponentContainer.LayoutConfig layoutConfig = mVideoView.getLayoutConfig(); // 播放器居中
        layoutConfig.width = ComponentContainer.LayoutConfig.MATCH_PARENT;
        layoutConfig.height = ComponentContainer.LayoutConfig.MATCH_PARENT;
        mController = new BasisVideoController(this);
        mController.removeSensorManager();
        initRecyclerView();
    }

    private void initRecyclerView() {
        listContainer = (ListContainer) findComponentById(ResourceTable.Id_recyclerView);
        mVideos = ConstantVideo.getVideoList();
        VideoRecyclerViewAdapter adapter = new VideoRecyclerViewAdapter(mVideos);
        adapter.setOnItemChildClickListener(this);
        listContainer.setItemProvider(adapter);
    }

    private void startFloatWindow() {
        mPipManager.startFloatWindow();
    }

    @Override
    protected void onActive() {
        super.onActive();
        mPipManager.resume();
    }

    @Override
    protected void onInactive() {
        super.onInactive();
        mPipManager.pause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mPipManager.reset();
    }

    @Override
    protected void onBackPressed() {
        ControlWrapper.defaultValue();
        if (mPipManager.onBackPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    public void onItemChildClick(int position) {
        startPlay(position, true);
    }

    /**
     * 开始播放
     *
     * @param position 列表位置
     * @param isRelease isRelease
     */
    protected void startPlay(int position, boolean isRelease) {
        if (mPipManager.isStartFloatWindow()) {
            mPipManager.stopFloatWindow();
        }
        if (mPipManager.getPlayingPosition() != COUNT_NUM && isRelease) {
            releaseVideoView();
        }
        if (mLastPos != COUNT_NUM) {
            Component itemView = listContainer.getComponentAt(mLastPos);
            if (itemView != null) {
                VideoRecyclerViewAdapter.Holder viewHolder = (VideoRecyclerViewAdapter.Holder) itemView.getTag();
                mController.removeControlComponent(viewHolder.mPrepareView);
                viewHolder.mPrepareView.onPlayStateChanged(ConstantKeys.CurrentState.STATE_IDLE);
            }
        }
        VideoInfoBean videoBean = mVideos.get(position);
        mVideoView.setUrl(videoBean.getVideoUrl());
        Component itemView = listContainer.getComponentAt(position);
        if (itemView == null) {
            return;
        }

        // 注意：要先设置控制才能去设置控制器的状态。
        mVideoView.setController(mController);
        mController.setPlayState(mVideoView.getCurrentPlayState());
        VideoRecyclerViewAdapter.Holder viewHolder = (VideoRecyclerViewAdapter.Holder) itemView.getTag();

        // 把列表中预置的PrepareView添加到控制器中，注意isPrivate此处只能为true。
        mController.addControlComponent(viewHolder.mPrepareView, true);
        PlayerUtils.removeViewFormParent(mVideoView);
        viewHolder.mPlayerContainer.addComponent(mVideoView, 0);
        mVideoView.start();
        mPipManager.setPlayingPosition(position);
        mLastPos = position;
    }

    private void releaseVideoView() {
        mVideoView.release();
        if (mVideoView.isFullScreen()) {
            mVideoView.stopFullScreen();
        }
        AbilityInfo.DisplayOrientation orientation = getContext().getAbilityInfo().getOrientation();
        if (orientation != AbilityInfo.DisplayOrientation.PORTRAIT) {
            this.setDisplayOrientation(AbilityInfo.DisplayOrientation.PORTRAIT);
        }
        mPipManager.setPlayingPosition(COUNT_NUM);
    }
}
